<template>
  <div class="friends-container">
    <div class="friends-header">
      <h2 class="header-title">我的好友</h2>
      <div class="header-actions">
        <button @click="goToRequests" class="requests-btn">
          <span class="btn-icon">📨</span>
          好友申请
        </button>
        <button @click="showAddFriendDialog = true" class="add-btn">
          <span class="btn-icon">➕</span>
          添加好友
        </button>
      </div>
    </div>

    <div class="friends-list">
      <div v-for="friend in friends" :key="friend.id" class="friend-item">
        <div class="friend-avatar">
          <span class="avatar-text">{{ friend.friend_user_avatar || friend.friend_user_name?.charAt(0) || '默' }}</span>
          <div class="online-indicator" :class="{ 'online': getFriendOnlineStatus(friend.friend_user_id) }"></div>
        </div>
        <div class="friend-info">
          <div class="friend-name">{{ friend.friend_user_name || '未知用户' }}</div>
          <div class="friend-status" :class="{ 'online': getFriendOnlineStatus(friend.friend_user_id) }">
            {{ getFriendOnlineStatus(friend.friend_user_id) ? '🟢 在线' : '⚪ 离线' }}
          </div>
        </div>
        <div class="friend-actions">
          <button @click="startChat(friend.friend_user_id)" class="chat-btn">
            <span class="btn-icon">💬</span>
            聊天
          </button>
          <button @click="deleteFriendHandler(friend.friend_user_id)" class="delete-btn">
            <span class="btn-icon">🗑️</span>
            删除
          </button>
        </div>
      </div>
    </div>

    <!-- 添加好友弹窗 -->
    <div v-if="showAddFriendDialog" class="dialog-overlay" @click="showAddFriendDialog = false">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h3 class="dialog-title">添加好友</h3>
          <button @click="showAddFriendDialog = false" class="close-icon">✕</button>
        </div>
        
        <div class="search-section">
          <div class="search-input-wrapper">
            <span class="search-icon">🔍</span>
            <input
              v-model="searchUsername"
              placeholder="输入用户名搜索"
              class="search-input"
              @keyup.enter="searchUserHandler"
            >
          </div>
          <button @click="searchUserHandler" class="search-btn">
            <span class="btn-icon">🔍</span>
            搜索
          </button>
        </div>

        <div v-if="searchResult" class="search-result">
          <div class="user-info">
            <div class="user-avatar">
              <span class="avatar-text">{{ searchResult.avatar || '默' }}</span>
            </div>
            <div class="user-details">
              <div class="user-name">{{ searchResult.username }}</div>
              <div class="user-id">ID: {{ searchResult.id }}</div>
            </div>
          </div>
          <button @click="sendFriendRequestHandler(searchResult.id)" class="add-friend-btn">
            <span class="btn-icon">➕</span>
            添加好友
          </button>
        </div>

        <div v-else-if="searchUsername && !searchResult" class="no-result">
          <div class="no-result-icon">🔍</div>
          <div class="no-result-text">未找到相关用户</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { getFriendList, searchUser, addFriend, deleteFriend, getOrCreateChatRoom, sendFriendRequest } from '@/api/friends'

import { checkLoginStatus, getCurrentUserId } from '@/utils/auth'

uni.showToast({ title: '进入好友页面', icon: 'none', duration: 1000 })

// 好友数据
const friends = ref([])
const showAddFriendDialog = ref(false)
const searchUsername = ref('')
const searchResult = ref(null)

// 在线状态管理
const friendsOnlineStatus = ref({})

// 更新好友在线状态
const updateFriendOnlineStatus = (userId, isOnline) => {
	friendsOnlineStatus.value[userId] = isOnline
	console.log('更新好友在线状态:', userId, isOnline)
}

// 更新好友状态列表
const updateFriendsOnlineStatus = (statusList) => {
	statusList.forEach(status => {
		friendsOnlineStatus.value[status.user_id] = status.is_online
	})
	console.log('更新好友状态列表:', statusList)
}

// 获取好友在线状态
const getFriendOnlineStatus = (friendId) => {
	return friendsOnlineStatus.value[friendId] || false
}

// 获取好友列表
const fetchFriendList = async () => {
  try {
    const res = await getFriendList()
    console.log('好友列表响应:', res)
    friends.value = res.data || []
  } catch (error) {
    console.error('获取好友列表失败:', error)
    uni.showToast({ title: '获取好友列表失败', icon: 'none' })
  }
}

// 搜索用户
const searchUserHandler = async () => {
  if (!searchUsername.value.trim()) {
    uni.showToast({ title: '请输入用户名', icon: 'none' })
    return
  }

  try {
    const res = await searchUser(searchUsername.value)
    console.log('搜索用户响应:', res)
    if (res.data && res.data.length > 0) {
      searchResult.value = res.data[0] // 取第一个搜索结果
    } else {
      searchResult.value = null
      uni.showToast({ title: '未找到相关用户', icon: 'none' })
    }
  } catch (error) {
    console.error('搜索用户失败:', error)
    uni.showToast({ title: '搜索用户失败', icon: 'none' })
  }
}

// 发送好友申请
const sendFriendRequestHandler = async (userId) => {
  try {
    const currentUserId = getCurrentUserId(true)
    if (!currentUserId) {
      uni.showToast({ title: '请先登录', icon: 'none' })
      return
    }

    await sendFriendRequest({
      from_user_id: currentUserId,
      to_user_id: userId,
      message: '我想和你成为好友'
    })
    
    uni.showToast({ title: '好友申请已发送', icon: 'success' })
    showAddFriendDialog.value = false
    searchUsername.value = ''
    searchResult.value = null
  } catch (error) {
    console.error('发送好友申请失败:', error)
    uni.showToast({ title: '发送好友申请失败', icon: 'none' })
  }
}

// 添加好友（保留原有逻辑作为备用）
const addFriendHandler = async (userId) => {
  try {
    const currentUserId = getCurrentUserId(true)
    if (!currentUserId) {
      uni.showToast({ title: '请先登录', icon: 'none' })
      return
    }

    await addFriend({
      user_id: currentUserId,
      friend_id: userId
    })
    uni.showToast({ title: '添加好友成功', icon: 'success' })
    showAddFriendDialog.value = false
    searchUsername.value = ''
    searchResult.value = null
    // 刷新好友列表
    fetchFriendList()
  } catch (error) {
    console.error('添加好友失败:', error)
    uni.showToast({ title: '添加好友失败', icon: 'none' })
  }
}

// 删除好友
const deleteFriendHandler = async (userId) => {
  try {
    const currentUserId = getCurrentUserId(true)
    if (!currentUserId) {
      uni.showToast({ title: '请先登录', icon: 'none' })
      return
    }

    uni.showModal({
      title: '确认删除',
      content: '确定要删除这个好友吗？',
      success: async (res) => {
        if (res.confirm) {
          await deleteFriend({
            user_id: currentUserId,
            friend_id: userId
          })
          uni.showToast({ title: '删除好友成功', icon: 'success' })
          // 刷新好友列表
          fetchFriendList()
        }
      }
    })
  } catch (error) {
    console.error('删除好友失败:', error)
    uni.showToast({ title: '删除好友失败', icon: 'none' })
  }
}

// 开始聊天
const startChat = async (userId) => {
  try {
    // 检查是否已有房间
    const res = await getOrCreateChatRoom(userId)
    uni.setStorageSync('roomId', res.data.roomId)
    uni.navigateTo({ url: '/pages/chat/chat' })
  } catch (error) {
    console.error('创建聊天房间失败:', error)
    uni.showToast({ title: '进入聊天失败', icon: 'none' })
  }
}

// 跳转到好友申请页面
const goToRequests = () => {
  uni.navigateTo({ url: '/pages/friends/requests' })
}

// 组件挂载时
onMounted(() => {
	if (!checkLoginStatus()) {
		uni.navigateTo({ url: '/pages/login/login' })
		return
	}

	fetchFriendList()
	
	// 监听WebSocket消息
	uni.$on('userStatusChange', (data) => {
		updateFriendOnlineStatus(data.userId, data.isOnline)
	})
	
	uni.$on('friendsStatusUpdate', (statusList) => {
		updateFriendsOnlineStatus(statusList)
	})
})

// 组件卸载时清理事件监听
onUnmounted(() => {
	uni.$off('userStatusChange')
	uni.$off('friendsStatusUpdate')
})
</script>

<style src="./friends.css"></style>